package com.lanou.quanttradedata.utils.javabean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class TuShareAPI {
    @Autowired
    RestTemplate template;
    /**
     * 用于向tushare平台发送请求，并接收到响应
     * @param api
     * @param params
     * @param fields
     * @return
     */
    public JSONObject get(String api, Map<String, String> params, List<String> fields) {
        Map<String, Object> allParam = new HashMap<>();
        allParam.put("api_name", api);
        allParam.put("token", Const.TUSHARE_TOKEN);
        // 请求参数
        allParam.put("params", params);
        // 设置 需要响应回来的字段
        if (fields != null && fields.size()>0) {
            StringBuffer buffer = new StringBuffer();
            int size = fields.size();
            for (int i = 0; i <size; i++) {
                buffer.append(fields.get(i));
                if(i!=size-1){
                    buffer.append(",");
                }
            }
            allParam.put("fields", buffer.toString());
        }
        //设置并发送请求，获取并返回响应
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map> entity = new HttpEntity<>(allParam, headers);
        String str = template.postForObject(Const.TUSHARE_BASE_URL,entity, String.class);
        JSONObject json = JSON.parseObject(str);
        return json;
    }
}
